package org.sja.log2traffic.dataStructures;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class CategoryTrackerEntity implements ICategoryTracker {
	
	Map<String, CounterForDateAndResponseTimeEntity> statsForCategories = new HashMap<String, CounterForDateAndResponseTimeEntity>();

	@Override
	public void foundCategory(String categoryName, DateAndResponseTimeEntity dateAndResponseTime){
		CounterForDateAndResponseTimeEntity counterForDateAndResponseTime = statsForCategories.get(categoryName);
		if (counterForDateAndResponseTime == null) {
			counterForDateAndResponseTime = new CounterForDateAndResponseTimeEntity(categoryName);
			statsForCategories.put(categoryName, counterForDateAndResponseTime);
		}
		counterForDateAndResponseTime.newDateAndResponseTime(dateAndResponseTime);
	}
	
	public CounterForDateAndResponseTimeEntity[] getSortedByCount(){
		CounterForDateAndResponseTimeEntity[] result = new CounterForDateAndResponseTimeEntity[statsForCategories.size()];
		statsForCategories.values().toArray(result);
		Arrays.sort(result, new Comparator<CounterForDateAndResponseTimeEntity>() {
			@Override
			public int compare(CounterForDateAndResponseTimeEntity o1, CounterForDateAndResponseTimeEntity o2) {
				long res = o2.getCount() - o1.getCount();
				if (res > Integer.MAX_VALUE){
					return Integer.MAX_VALUE;
				} else if (res < Integer.MIN_VALUE){
					return Integer.MIN_VALUE;
				} else {
					return (int)res;
				}
			}
		});
		return result;
	}
		
}
